﻿package com.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.entity.ContactItems;
import com.entity.ProductCategory;
import com.entity.Production;
import com.service.ContactItemsService;
import com.service.ProductCategoryService;
import com.service.ProductionService;

public class BaseController {
	private static final Logger logger = Logger.getLogger(BaseController.class);
	protected void initCommon(HttpServletRequest request, ProductCategoryService pcs, ContactItemsService cis, ProductionService ps){
		List<ProductCategory> categoryList = pcs.findAllCategory();
		for(ProductCategory category:categoryList){
			category.setSize(ps.countByCategory(category.getId()));
		}
		request.setAttribute("categoryList", categoryList);
		
		List<ContactItems> contactList = cis.findAllItems();
		request.setAttribute("contactList", contactList);
		
		List<ProductCategory> bottomList = pcs.findBottom();
		for(ProductCategory category:bottomList){
			List<Production> productions = ps.findByCategoryInPage(category.getId(), 0, 3);
			category.setProducts(productions);
			category.setSize(productions.size());
		}
		request.setAttribute("bottomList", bottomList);
	}
	
	/**
	 * 将json数据输出到客户端
	 * 
	 * @param json
	 */
	public void outJson(String json, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			response.setContentType("text/html;charset=utf-8");
			out = response.getWriter();
			out.print(json);
			out.flush();
			out.close();
		} catch (IOException ex) {
			logger.error("向客户端输出信息失败！原因：" + ex.getMessage());
		} finally {
			out.close();
		}
	}
	
	public String genListJson(int total, JSONArray array){
		JSONObject obj = new JSONObject();
		obj.put("total", total);
		obj.put("rows", array);
		return obj.toJSONString();
	}
	
	public int getStart(HttpServletRequest request){
		String page = request.getParameter("page");
		if(StringUtils.isEmpty(page))
			page = "1";
		return (Integer.parseInt(page)-1)*getLimit(request);
	}
	
	public int getLimit(HttpServletRequest request){
		String rows = request.getParameter("rows");
		if(StringUtils.isEmpty(rows))
			rows = "10";
		return Integer.parseInt(rows);
	}
	
}
